import MusenumUserTimesModel from "../model/musenumUserTimes";
import OpenCvHelper from "../middleware/openCvHelper";
import { blockTick, createOrder, getCheckTime } from "../thirdServices/museumApi";
import AppointOrderModel from "../model/appointOrder";
import { aesEncrypt, sleep } from "../utils";

class MuseumHelper {
  async buy(poolVO, touristList: any[]) {
    const user: any = await this.getCreateUser(poolVO.currentDate, touristList.length);
    if (user) {
      const isBuy = await this.blockTick(user, poolVO, touristList);
      if (isBuy) {
        await this.addOrder(user.phone, poolVO, touristList);
        await this.updateTimes(user)
      }
      return isBuy;
    } else {
      return false;
    }
  }

  addOrder(buyUser, poolVO, touristList) {
    // 添加订单
    const orderInfo = {
      createUser: buyUser,
      appointDate: poolVO.currentDate,
      appointTime: poolVO.hallScheduleId,
      touristInfo: JSON.stringify(touristList),
      platform: 1,
    };
    try {
      AppointOrderModel.insert(orderInfo); 
    } catch (error) {
      
    }
  }

  async updateTimes(user) {
    const times = user.times + 1;
    try {
      await MusenumUserTimesModel.update({ times }, user.id);
    } catch (error) {
      
    }
  }

  async getCreateUser(date: string, touristNum: number) {
    const model = await MusenumUserTimesModel.findOneAvailable(date, 5 - touristNum);
    if (model) {
      const user = {
        userId: model.getDataValue('userid'),
        token: model.getDataValue('token'),
        phone: model.getDataValue('phonenumber'),
        id: model.getDataValue('id'),
        times: model.getDataValue('times'),
      }
      return user;
    }
    return;
  }

  async blockTick(user, poolVO, ticketList) {
    const secretkey = false;
    const { data } = await getCheckTime();

    const macIp = data.split('"')[9];
    const time = data.substr(26, 10) + "000";
    const hallId = poolVO.hallId;
    const date = poolVO.currentDate.replace(/-/g, "/")
    const scheduleId = poolVO.hallScheduleId;
    const type = secretkey ? '12' : '2'
    const ticket = secretkey ? "mjnkHYmu0jpURBTQ" : "AyrKJRXPO3nR5Abc";
    const nonce = aesEncrypt("".concat(user.userId, ":").concat(time, ":").concat(date, ":").concat(hallId, ":").concat(scheduleId, ":").concat(type), ticket);
    const blockRes = await blockTick(user.token, nonce);
    if (blockRes.data.code === 200) {
      const blockData = blockRes.data.data;
      // // 去除Base64头部信息并转换成Buffer对象
      // // 原图
      const originData = Buffer.from(blockData.originalImageBase64, 'base64');
      // // 目标物 
      const sawData = Buffer.from(blockData.jigsawImageBase64, 'base64');
      const cv = new OpenCvHelper();
      await sleep(1000);
      const point = await cv.find(originData, sawData);
      const isBuy = await this.createOrder(point, poolVO, blockData, macIp, ticketList, user.token);
      return isBuy;
    }
    return false;
  }

  async createOrder(point: any, poolVO: any, captchaData: any, macIp: string, ticketList: any[], userToken) {
    const { secretKey, token } = captchaData;
    const pointJson = secretKey ? aesEncrypt(JSON.stringify(point), secretKey) : JSON.stringify(point);
    const gloSecretkey = null;

    // ticketPriceId 先写死8  https://wxmini.chnmuseum.cn/prod-api/pool/ingore/getPriceByScheduleId?hallId=1&openPerson=1&queryDate=2024%2F02%2F21&saleMode=1&scheduleId=3&p=wxmin
    const isChild = false;
    const ticketInfoList = ticketList.map(item => {
      return {
        status: 0,
        saleMode: gloSecretkey ? 2 : 1,
        platform: gloSecretkey ? 12 : 2,
        hallId: poolVO.hallId,
        hallScheduleId: poolVO.hallScheduleId,
        cinemaFlag: 0,
        ticketPriceId: 8,
        certificate: item.idType,
        certificateInfo: item.idNo,
        userName: item.name,
        useDate: `${poolVO.currentDate} 00:00:00`,
        isChildFreeTicket: isChild ? 1 : 0,
        realNameFlag: 1
      };
    });
    const data = {
      useTicketType: 1,
      ticketNum: ticketInfoList.length || 0,
      date: poolVO.currentDate,
      childTicketNum: 0,
      poolFlag: 1,
      saleMode: gloSecretkey ? 2 : 1,
      realNameFlag: 1,
      pointJson,
      captchaToken: token,
      platform: gloSecretkey ? 12 : 2,
      scanToken: gloSecretkey,
      ticketInfoList,
      p: 'wxmini'
    };
    
    let ip = '';
    try {
      if (macIp) {
        const key = gloSecretkey ? 'mjnkHYmu0jpURBTQ' : 'AyrKJRXPO3nR5Abc';
        ip = aesEncrypt(''.concat(macIp), key);
      }
    } catch (e) {
      console.log(e);
    }
    try {
      const orderinfo = await createOrder(userToken, data, ip);
      if (orderinfo.data.code === 200) {
        console.log("购票成功");
        return true;
      } else {
        console.log(orderinfo.data);
      } 
    } catch (error) {
      console.log('dddd');
      console.log(error)
    }

    return false;
  }
}

export default MuseumHelper;